package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import cn.wolfcode.wolf2w.util.Consts;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void setSendVerifyCode(String phone, String code) {

        //创建key
        String key = RedisKeys.VERIFY_CODE.join(phone);

        //给验证码设置时间
        //第一个是key 第二个是value 第三个是设置时间  第四个 时间参数
        redisTemplate.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getverifyCode(String phone) {
        //创建key
        String key = RedisKeys.VERIFY_CODE.join(phone);
        //获取key
        String code = redisTemplate.opsForValue().get(key);
        return code;
    }

    @Override
    public String setToken(UserInfo user) {
        String token = UUID.randomUUID().toString().replace("-", "");
        //创建key
        String key = RedisKeys.USER_TOKEN.join(token);
        String value=JSON.toJSONString(user);
        redisTemplate.opsForValue().set(key, value, RedisKeys.USER_TOKEN.getTime(), TimeUnit.SECONDS);
        return token;
    }

    @Override
    public UserInfo getUserInfoToken(String token) {
        //没值返回null
        if (!StringUtils.hasLength(token)){
            return null;
        }
        String key = RedisKeys.USER_TOKEN.join(token);
        //判断是否有key
        if (redisTemplate.hasKey(key)){
            String userStr = redisTemplate.opsForValue().get(key);

            if (StringUtils.hasLength(userStr)){
                UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);
                //重置时间
                redisTemplate.expire(key,RedisKeys.USER_TOKEN.getTime() , TimeUnit.SECONDS);
                return userInfo;
            }
        }
        return null;
    }

}
